package com.mind.ridge.service.backend.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mind.ridge.mapper.backend.CategoryMapper;
import com.mind.ridge.pojo.backend.Category;
import com.mind.ridge.service.backend.CategoryService;
import com.mind.ridge.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Mind
 */
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Override
    public R<IPage> page(Integer currentPage, Integer pageSize) {
        if (currentPage == null || pageSize == null) {
            return R.error("查询失败");
        }
        log.info(currentPage + ";" + pageSize);
        //创建IPage对象
        IPage<Category> page = new Page<>(currentPage, pageSize);

        //设置按照修改时间排序排序
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Category::getUpdateTime);

        //分页查询
        this.page(page, lqw);

        //返回Page对象
        return R.success(page);
    }

    @Override
    public R<String> delById(Long id, HttpServletRequest request) {

        //创建新用户设置要删除的数据
        Category category = new Category();
        category.setId(id);

        //设置当前的被删除的对象的修改日期以及修改人
        category.setUpdateTime(LocalDateTime.now());
        Long operator = (Long) request.getSession().getAttribute("id");
        category.setUpdateUser(operator);

        boolean b = this.removeById(category);
        return b ? R.success("删除成功") : R.error("删除失败，该用户可能已被删除");
    }

    @Override
    public R<String> addCategory(Category category) {

        if (category == null) {
            return R.error("未知错误!");
        }

        return save(category) ? R.success("添加成功") : R.error("错误！！");
    }

    @Override
    public R<String> updateCategory(Category category) {
        if (category == null) {
            return R.error("未知错误");
        }
        return updateById(category) ? R.success("修改成功") : R.error("修改失败，该用户或已被删除");
    }

    @Override
    public R listType(Category category) {
        if (category == null) {
            return R.error("数据为空！");
        }
        Integer type = category.getType();
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType() != null, Category::getType, type);
        List<Category> list = list(queryWrapper);
        return R.success(list);
    }
}
